<template>
<div class="login">
  <el-form class="container" ref="loginRef" :model="loginForm" :rules="loginrules">
    <el-form-item class="avatar">
      <img src="../assets/avatar.jpg" alt="">
    </el-form-item>
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" prefix-icon="myicon myicon-user"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" @keyup.enter.native="handleLogin" v-model="loginForm.password" prefix-icon="myicon myicon-key"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleLogin" class="login-btn">登录</el-button>
    </el-form-item>
  </el-form>
 </div>
</template>

<script>
import { login } from '@/api'
export default {
  data () {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 校验检测字段
      loginrules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    handleLogin () {
      /* this.$refs.loginRef.validate()校验，其中的回调函数
          的参数是一个布尔值，表示校验是否通过
      */
      this.$refs.loginRef.validate((isPass) => {
        if (isPass) {
          // 发请求
          login(this.loginForm)
            .then(res => {
              // console.log(res)
              if (res.data.meta.status === 200) {
                localStorage.setItem('username', res.data.data.username)
                localStorage.setItem('mytoken', res.data.data.token)
                this.$router.push({ name: 'home' })
              } else {
                this.$message.error(res.data.meta.msg)
              }
            })
            .catch(err => {
              console.log('err', err)
            })
        } else {
          this.$message.error('校验未通过，请重新输入！')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .login {
    position: fixed;
    width: 100%;
    height: 100%;
    background-color: #2f4050;

    .container {
      position: absolute;
      left: 0;
      right: 0;
      width: 400px;
      padding: 0px 40px 15px 40px;
      margin: 250px auto;
      background: white;
      border-radius: 5px;
      .avatar {
        position: relative;
        left: 50%;
        width: 120px;
        height: 120px;
        margin-left: -60px;
        margin-top: -60px;
        box-sizing: border-box;
        border-radius: 50%;
        border: 10px solid #fff;
        box-shadow: 0 1px 5px #ccc;
        overflow: hidden;
        img{
          width: 100%;
        }
      }
      .login-btn {
        width: 100%;
      }
    }
  }
</style>
